<template>
  <div class="user-add">
    <div class="page-title">
      <div>居民信息录入</div>
    </div>

    <el-card>
      <el-alert
        :title="prompt"
        type="info">
      </el-alert>

      <div class="step">
        <el-steps :active="2" :align-center="true" :center="true">
          <el-step title="线下采集"></el-step>
          <el-step title="工作人员录入"></el-step>
          <el-step title="负责人审批入库"></el-step>
        </el-steps>
      </div>

      <el-form :model="user" :rules="userRule" ref="user" class="user-form" label-position="top">
        <el-row :gutter="40">
          <el-col :sm="24" :md="12">
            <el-form-item label="居民姓名" prop="username">
              <el-input v-model="user.username" size="small"></el-input>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="身份证号" prop="code">
              <el-input v-model="user.code" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="性别">
              <el-select v-model.number="user.sex" size="small">
                <el-option label="男性" :value="0"></el-option>
                <el-option label="女性" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="电话号码">
              <el-input v-model="user.phone" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="微信号/QQ号">
              <el-input v-model="user.tencent" size="small"></el-input>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="兵役状况">
              <el-select v-model.number="user.army" size="small">
                <el-option label="未服兵役" :value="0"></el-option>
                <el-option label="兵役中" :value="1"></el-option>
                <el-option label="已服兵役" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="创建缘由">
              <el-select v-model.number="user.createAs" size="small">
                <el-option label="信息录入" :value="0"></el-option>
                <el-option label="嫁娶进入" :value="1"></el-option>
                <el-option label="新生儿" :value="2"></el-option>
                <el-option label="其他" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="身份分类" prop="tag">
              <el-select v-model="user.tag" multiple placeholder="请选择" size="small">
                <el-option
                  v-for="item in tag"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="享受补助">
              <el-select v-model="user.allowance" multiple placeholder="请选择" size="small">
                <el-option
                  v-for="item in allowance"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="家庭信息">
              <el-select
                v-model="user.family"
                multiple
                filterable
                remote
                placeholder="请输入户主姓名以选择"
                size="small"
                :remote-method="searchFamily"
                :loading="loadFamily">
                <el-option
                  v-for="item in searchTemp"
                  :key="item._id"
                  :label="item.label"
                  :value="item._id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :sm="24" :md="12">
            <el-form-item label="个人地址">
              <el-input type="textarea" v-model="user.address" size="small">
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :sm="24" :md="12">
            <el-form-item label="备注信息">
              <el-input type="textarea" v-model="user.remark"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24"></el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="个人照片">
              <el-upload
                class="avatar-uploader"
                name="headPhoto"
                action="/api/upload/head"
                :headers="token"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageURL" :src="imageURL" class="avatar"> <i v-else
                                                                        class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :md="12">
            <el-form-item label="资料照片">
              <el-upload
                class="upload-demo"
                name="pagePhoto"
                action="/api/upload/page"
                :headers="token"
                :on-success="handlePageSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="imageList">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过8MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="oper-box">
        <el-button type="primary" @click="submit" :loading="loading" size="small">确认无误，创建
        </el-button>
      </div>

      <el-dialog
        title="图片预览"
        :visible.sync="dialogVisible">
        <img class="image-review" :src="imageReview">
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
  import {httpPost, httpGet} from '../../util/api'

  export default {
    name: 'user-add',
    data() {
      return {
        searchTemp: [],
        loadFamily: false,
        reading: false,
        loading: false,
        dialogVisible: false,
        userRule: {
          username: [
            { required: true, message: '居民姓名必填', trigger: 'blur' },
          ],
          code: [
            { required: true, message: '身份证号码必填', trigger: 'blur' },
            { min: 15, max: 18, message: '请准确填写身份证号码', trigger: 'change' },
          ],
          tag: [
            { required: true, type: 'array', message: '请至少选择一个该项信息', trigger: 'blur' },
          ],
        },
        tag: [], // 身份标签
        allowance: [], //所属群组集id
        imageURL: '',
        imageList: [],
        imageReview: '',
        prompt: '填写说明：如实录入居民信息。"居民身份" 选项需要点击左侧菜单新建身份分类， "居民分组"在创建之后进行操作录入。',
        user: {
          username: '',
          code: '',
          sex: 0,
          phone: '',
          tencent: '',
          army: 0,
          createAs: 0, // 创建缘由
          tag: [], // 身份标签
          allowance: [], //所属群组集id 享受补助
          address: '',
          remark: '', //个人信息
          headPicture: '',
          pages: [], // 照片列表
          state: 200, //当前状态
          creator: '', // 创建者
          family: [],
        },
      }
    },
    computed: {
      token() {
        return { 'token': btoa(JSON.stringify(this.$store.state.user)) }
      },
    },
    methods: {
      searchFamily(query) {
        if (query !== '') {
          this.loadFamily = true
          setTimeout(() => {
            this.loadFamily = false
            this.searchTemp = httpGet(`/cell/family?filter={"name": "^${query}"}`)
              .then((response) => {
                this.searchTemp = response.data.data
                this.loadFamily = false
              })
          }, 200)
        } else {
          this.searchTemp = []
        }
      },
      loadOption() {
        this.reading = true
        httpGet('/cell/tag').then((response) => {
          this.tag = response.data.result.data
        }).then(() => {
          httpGet('/cell/allowance').then((response) => {
            this.allowance = response.data.result.data
            this.reading = false
          })
        }).catch((err) => {
          console.log(err)
        })
      },
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.$message.success('上传成功')
          this.user.headPicture = res.msg
          this.imageURL = URL.createObjectURL(file.raw)
        } else {
          this.$message.error('上传失败')
        }
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 8
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 8MB!')
        }
        return isLt2M && true
      },
      handlePageSuccess(res, file) {
        if (res.code === 200) {
          this.user.pages.push(res.msg)
          this.$message.success('上传成功')
        } else {
          this.$message.error('上传失败')
        }
      },
      handlePreview(file) {
        this.imageReview = file.url
        this.dialogVisible = true
      },
      handleRemove(file, fileList) {
        const index = this.user.pages.indexOf(file.response.msg)
        this.user.pages.splice(index, 1)
      },
      submit() {
        this.$refs['user'].validate((valid) => {
          if (!valid) {
          } else {
            httpPost('/user', this.user).then((response) => {
              this.$message.success('创建成功')
            })
          }
        })
      },
    },
    created() {
      this.loadOption()
    },
  }
</script>


<style lang="scss">
  @import "../../scss/theme";

  .user-add {
    /*padding: 0 24px;*/
    .oper-box {
      margin: 40px auto;
      display: flex;
      justify-content: center;
    }
    .image-review {
      width: 100%;
    }
  }

  .el-alert {
    margin-bottom: 20px;
    /*background-color: #fff;*/
    /*color: #333;*/
    /*border: 1px solid #c9c9c9;*/
    /*.el-alert__closebtn {*/
    /*color: #333;*/
    /*}*/
  }

  .user-form {
    .el-select {
      width: 100%;
    }
  }

  .el-form-item {
    padding: 8px 0;
  }

  .pull-btn {
    width: 100%;
    margin: 20px auto;
    padding: 20px;
    border-bottom: 1px solid $dark;
    display: flex;
    justify-content: flex-end;
  }

  .el-card {
    background-color: $background;
    .el-card__header {
      padding: 4px 20px;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .user-add {
    .el-card {
      margin-bottom: 20px;
    }
    .step {
      width: 100%;
      padding: 20px;
      margin: 12px auto;
    }
  }
</style>
